﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using System.IO;
using System.Xml;
using SharePointOfView.Utilities;
using SharePointOfView.Diagnostics;
using SharePointOfView.ExtensionMethods;

namespace SharePointOfView.EventReceivers
{
    public class LookupCreationFeatureReceiver : SPFeatureReceiver
    {
        /// <summary>
        /// Occurs after a Feature is activated.
        /// Get values for properties named 'lookupFile' and 'resourceFile'. The key 'lookupfile' is mandatory
        /// This code is based on the solution provided by Chris O'Brien at http://www.codeplex.com/SP2007LookupFields  
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPWeb web = site.RootWeb;

            try
            {
                string filePath = Path.Combine(properties.Definition.RootDirectory, properties.Feature.Properties["lookupFile"].Value);
                string resourceFile = string.Empty;

                try
                {
                    resourceFile = properties.Feature.Properties["resourceFile"].Value;
                }
                catch { }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsMgr.AddNamespace("def", "http://schemas.microsoft.com/sharepoint/");

                XmlNodeList fields = xmlDoc.SelectNodes(".//def:Field", nsMgr);

                foreach (XmlNode field in fields)
                {
                    string listName = string.Empty;

                    foreach (XmlAttribute attribute in field.Attributes)
                    {
                        if (attribute.Value.StartsWith("$Resources:") && !string.IsNullOrEmpty(resourceFile))
                        {
                            attribute.Value = Localization.GetResource(attribute.Value.Replace("$Resources:", string.Empty), resourceFile, web.Language);
                        }

                        if (attribute.Name == "List")
                        {
                            listName = attribute.Value;
                        }
                    }

                    SPList referencedList;

                    if (listName != String.Empty && web.Lists.SovTryGet(listName, out referencedList))
                    {
                        field.Attributes["List"].Value = referencedList.ID.ToString();
                        string realFieldToCreate = field.OuterXml;

                        string lookupColumnName = web.Fields.AddFieldAsXml(realFieldToCreate);

                        SPFieldLookup lookupColumn = web.Fields.GetFieldByInternalName(lookupColumnName) as SPFieldLookup;

                        lookupColumn.LookupWebId = web.ID;
                        lookupColumn.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                ULS.WriteError("Error activating lookup creation feature. Message : " + ex.Message, "SharePointOfView");
                site.Features.Remove(properties.Feature.DefinitionId);
                throw ex;
            }
            finally
            {
                web.Dispose();
            }
        }

        /// <summary>
        /// Occurs when a Feature is deactivated.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;
            SPWeb web = site.RootWeb;

            try
            {
                string filePath = Path.Combine(properties.Definition.RootDirectory, properties.Feature.Properties["lookupFile"].Value);

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(filePath);

                XmlNamespaceManager nsMgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsMgr.AddNamespace("def", "http://schemas.microsoft.com/sharepoint/");

                XmlNodeList fields = xmlDoc.SelectNodes(".//def:Field/@ID", nsMgr);

                Guid lookupfieldGuid;
                foreach (XmlNode field in fields)
                {
                    lookupfieldGuid = new Guid(field.Value);

                    SPFieldLookup lookupColumn = web.Fields[lookupfieldGuid] as SPFieldLookup;
                    lookupColumn.Delete();
                }
            }
            catch (Exception ex)
            {
                ULS.WriteInformation("Error de-activating lookup creation feature. Message : " + ex.Message, "SharePointOfView");
            }

            web.Dispose();
        }

        #region Not Used
        /// <summary>
        /// Occurs after a Feature is installed.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {

        }

        /// <summary>
        /// Occurs when a Feature is uninstalled.
        /// </summary>
        /// <param name="properties">An <see cref="T:Microsoft.SharePoint.SPFeatureReceiverProperties"></see> object that represents the properties of the event.</param>
        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {

        }
        #endregion
    }
}
